package main

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"reflect"
	"strconv"
	"strings"
	"time"
)

//
//import (
//	"encoding/csv"
//	"sort"
//	"strings"
//
//	"fmt"
//	_ "github.com/go-sql-driver/mysql"
//	"github.com/google/uuid"
//	"github.com/jmoiron/sqlx"
//	"io"
//	"log"
//	"math/rand"
//	"os"
//	"strconv"
//	"time"
//)
//var (
//	database     *sqlx.DB //mysql连接对象//
//	userPool []UserData
//	userOffset int
//	timePool []int
//)
//
////把字母转为数字
//func getNumByLetter(letter string) int{
//	result := 0
//	for i :=0; i < len(letter); i++ {
//		temp := letter[i]
//		if temp <'A' || temp > 'Z' {
//			return result - 1
//		}
//		num := int(temp - 'A' + 1 )
//		result = result * 26 + num
//		//fmt.Println("num", result)
//	}
//	return result - 1
//}
//
////局数等到随机的分数
//func randomScore(score, count, min, max int)[]int{
//	var retlist []int
//	score -= min*count
//	for count > 1 {
//		maxRemain := score/count*2
//		if maxRemain > max {
//			maxRemain = max
//		}
//		//fmt.Println("maxRemain", maxRemain, score, count, min)
//		ret := RandInts(0, maxRemain - min)
//		score -= ret
//		count --
//		retlist = append(retlist, ret + min)
//	}
//	retlist = append(retlist, score + min)
//	return retlist
//}
//func RandInts(min, max int) int {
//	rr := rand.New(rand.NewSource(time.Now().UnixNano() * rand.Int63n(9999)))
//	//fmt.Println(min, max, max - min + 1)
//	return rr.Intn(max - min + 1) + min
//}
//
////对局id
//func CreateRefId(playType int) string {
//	serverId := RandInts(1,3)
//	return strconv.Itoa(int(serverId)) + "_" + strconv.Itoa(int(playType)) + "_" + uuid.New().String()
//}
//
//
////连接mysql
//func initMysql() {
//	fmt.Printf("StartDB...")
//	var err error
//	//Log.Printf("mysql config, host:%s, name:%s, name:%s", MysqlConfigViper_.GetString("host"), MysqlConfigViper_.GetString("name"), MysqlConfigViper_.GetString("username"))
//	connStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true&loc=Local&charset=utf8",
//		"root", "f3bc7ec833F98e491939e74a90d875", "120.76.201.244:3306", "indiaGame")
//	database, err = sqlx.Connect("mysql", connStr)
//	if err != nil {
//		panic(err)
//	}
//	database.DB.SetMaxOpenConns(500)
//	database.DB.SetMaxIdleConns(100)
//	database.DB.SetConnMaxLifetime(time.Second * 0)
//	fmt.Printf("The Db is: %v \n", database)
//}
//func mysqlReadOne(){
//	dest := &UserData{}
//	sql := "select * from india_user where playType=? limit ?"
//	err := database.Get(dest, sql, 113, 1)
//	if err != nil {
//		fmt.Printf("DBCache.Get failed, sql:%s, dest:%+v, err:%+v", sql, dest, err)
//		return
//	}
//	fmt.Println()
//	fmt.Println("select succ:", dest)
//}
////查户信息
//func queryUser(playType int, limit int, offset int) []UserData{
//	sql := fmt.Sprintf("select * from india_user where playType=%d limit %d offset %d", playType, limit, offset)
//	results, err := database.Query(sql)
//	if err != nil {
//		panic(err.Error())
//	}
//	userArr := []UserData{}
//	for results.Next() {
//		var data UserData
//		err = results.Scan(&data.Id, &data.RegTime, &data.Region, &data.PlayType)
//		if err != nil {
//			//panic(err.Error())
//			fmt.Println("ERROR scan ", err)
//			continue
//		}
//		userArr = append(userArr, data)
//	}
//	return userArr
//}
//
////取用户信息
//func getUser() UserData{
//	if len(userPool) == 0 {
//		userPool = queryUser(113, 100, 100 * userOffset)
//		userOffset = userOffset + 1
//		//fmt.Println("userOffset", userOffset)
//		//打乱数据
//		for i := len(userPool) - 1; i > 0; i-- {
//			num := rand.Intn(i + 1)
//			userPool[i], userPool[num] = userPool[num], userPool[i]
//		}
//	}
//	user := userPool[0]
//	userPool = append(userPool[1:])
//	return user
//}
//
//func getTime(date string, num int) int {
//	if len(timePool) == 0 {
//		timePool = getTimeList(date, num)
//	}
//	timeNum := timePool[0]
//	timePool = append(timePool[1:])
//	fmt.Println("getTime", time.Unix(int64(timeNum),0))
//	return timeNum
//}
//
////写入数据库
//func writeRummyData(data *RummyData) {
//	sql := "insert into india_round_rummy(createdAt, uid, region, playType, playSubType, level, platformCommission, refId)" +
//			"values(:createdAt, :uid, :region, :playType, :playSubType, :level, :platformCommission, :refId)"
//	_, err := database.NamedExec(sql, data)
//	if err != nil {
//		fmt.Printf("writeRummyData ERROR sql:%v, err:%+v \n", sql, err)
//		return
//	}
//	//fmt.Printf("writeRummyData success sql:%v \n", sql)
//}
//
//type RummyDataList []RummyData
//func (r RummyDataList) Len() int {
//	return len(r)
//}
//func (r RummyDataList) Swap(i, j int) {
//	r[i], r[j] = r[j], r[i]
//}
//func (r RummyDataList) Less(i, j int) bool{
//	return r[j].CreatedAt.Unix() < r[i].CreatedAt.Unix()
//}
//func writeRummyDataList(dataList []RummyData) {
//	if len(dataList) <= 0 {
//		return
//	}
//	//按时间排序
//	sort.Sort(sort.Reverse(RummyDataList(dataList)))
//	for _, rummyData := range dataList {
//		fmt.Printf("rummyData:%v \n", rummyData)
//		writeRummyData(&rummyData)
//	}
//}
//
//
//type UserData struct {
//	Id       int       `json:"id" db:"id"`
//	RegTime  time.Time `json:"regTime" db:"regTime"`
//	Region   string    `json:"region" db:"region"`
//	PlayType int       `json:"playType" db:"playType"`
//}
//
//type RummyData struct {
//	CreatedAt          time.Time `json:"createdAt" db:"createdAt"`
//	Uid                int       `json:"uid" db:"uid"`
//	Region             string    `json:"region" db:"region"`
//	PlayType           int       `json:"playType" db:"playType"`
//	PlaySubType        int       `json:"playSubType" db:"playSubType"`
//	Level              float32   `json:"level" db:"level"`
//	PlatformCommission float32   `json:"platformCommission" db:"platformCommission"`
//	RefId              string    `json:"refId" db:"refId"`
//}
//
//func getRandTimeByWeight()int{
//	timeweight := [...]int{85,66,52,43,33,22,11,15,20,25,28,30,38,40,38,55,60,65,63,68,71,75,70,66,75,80,85,90,100,90,80,75,66,68,74,66,88,80,95,88,90,100,100,100,80,70,75,80}
//	for i := 1; i< 48; i++ {
//		timeweight[i] += timeweight[i-1]
//	}
//	ret := RandInts(1, timeweight[47])
//	dex := 0
//	for i := 0; i< 48; i++ {
//		if ret <= timeweight[i] {
//			dex = i
//			break
//		}
//	}
//	return dex
//}
//
////取随机时间
//func getRandTime(date string) int{
//	arr := strings.Split(date, "/")
//	str := ""
//	for _, v := range arr {
//		if len(v) == 1 {
//			v = "0" + v
//		}
//		str = str + "/" + v
//	}
//	str = strings.TrimLeft(str, "/")
//	fmt.Println("strDate", str)
//
//	//随机时间
//	timeObj, _ := time.Parse("2006/01/02", str)
//	fmt.Println("timeNum", timeObj, timeObj.Unix())
//	timeNum := timeObj.Unix()
//	min := getRandTimeByWeight()*1800
//	ret := int(timeNum-8*3600) + RandInts(min, min+1800)
//	return ret
//}
//
////取一天的时间列表
//func getTimeList(date string, num int) (timeList []int) {
//	for i := 0; i < num; i++ {
//		t := getRandTime(date)
//		timeList = append(timeList, t)
//	}
//	sort.Ints(timeList)
//	return timeList
//}
//
//func insertData()  {
//	fmt.Println("test")
//	//准备读取文件
//	fileName := "E:\\doc\\data.csv"
//	fs, err := os.Open(fileName)
//	if err != nil {
//		log.Fatalf("can not open the file, err is %+v", err)
//	}
//	defer fs.Close()
//	//我需要用到的字段
//	dataMap := map[string][]string{
//		"0.05":    []string{"A", "H", "I", "K"}, //0.05
//		"0.1":     []string{"A", "O", "P", "R"}, //0.1
//		"0.25":    []string{"A", "V", "W", "Y"}, //0.25
//		"0.5":     []string{"A", "AC", "AD", "AF"}, //0.5
//		"1":       []string{"A", "AJ", "AK", "AM"}, //1
//		"2":       []string{"A", "AQ", "AR", "AS"}, //2
//		"5":       []string{"A", "AX", "AY", "BA"}, //5
//		"10":      []string{"A", "BE", "BF", "BH"}, //10
//		"50":  []string{"A", "BL", "BN", "BM"}, //pool50
//		"100": []string{"A", "BQ", "BS", "BR"}, //pool100
//	}
//	r := csv.NewReader(fs)
//
//	//针对大文件，一行一行的读取文件
//	for i:=0; i<4; i++ {
//		row, err := r.Read()
//		if err != nil && err != io.EOF {
//			log.Fatalf("can not read, err is %+v", err)
//		}
//		if err == io.EOF {
//			break
//		}
//		if i < 2 {
//			continue
//		}
//		rummyDataList := []RummyData{}
//		dataArr := []string{}
//		for roomType, letterArr := range dataMap {
//			fmt.Println("roomType", roomType)
//			dataArr = []string{}
//			for _, v := range letterArr {
//				num := getNumByLetter(v)
//				data := row[num]
//				if data == "" {
//					data = "0"
//				}
//				//fmt.Printf(" %v %+v ", v, data)
//				dataArr = append(dataArr, data)
//			}
//			fmt.Printf("%v \n", dataArr)
//			/*取到字段生成数据
//			表里的字段顺序是这样的：
//			时间、用户ID、用户所在地、玩法、场次（桌球：入场费、rummy：底分、德州：小盲）、抽水金额、对局ID
//			非pool50和pool100 单局最小分数2最大分数400
//			pool50和pool100 单局最小人次1最大人次5
//
//			dataArr -> 日期， 局数， 单局抽水， 总分
//			*/
//			//局数列表
//			allScore, _ := strconv.Atoi(dataArr[3])
//			count, _ := strconv.Atoi(dataArr[1])
//			charge, _ := strconv.ParseFloat(dataArr[2],2)
//			dataDate := dataArr[0]
//			if count == 0 || allScore == 0 || dataDate == "" || charge <= 0 {
//				continue
//			}
//			roundArr := randomScore(allScore, count, 2, 400)
//			fmt.Printf("allScore:%v, count:%v roundArr:%v \n", allScore, count, roundArr)
//
//			for _, score := range roundArr {
//				user := getUser()
//				date := getTime(dataDate, count) //根据
//				uid := user.Id
//				playType := user.PlayType
//				playSubType := 1
//				if roomType == "50" || roomType == "100" {
//					playSubType = 2
//				}
//				platformCommission := float64(score) * charge//
//				refId := CreateRefId(113)
//				region := user.Region
//				level, _ := strconv.ParseFloat(roomType, 2)
//
//				rummyData := RummyData{
//					time.Unix(int64(date), 0),
//					uid,
//					region,
//					playType,
//					playSubType,
//					float32(level),
//					float32(platformCommission),
//					refId,
//				}
//				rummyDataList = append(rummyDataList, rummyData)
//			}
//		}
//		writeRummyDataList(rummyDataList)
//
//	}
//
//}
//
//func test(){
//	//getNumByLetter("AA")
//	//res := randomScore(5732,0, 2, 400)
//	//fmt.Println("res",res)
//	//arr := queryUser(113, 1, 1)
//	//fmt.Println("arr", arr)
//	user := getUser()
//	fmt.Println(user)
//	user = getUser()
//	fmt.Println(user)
//	user = getUser()
//	fmt.Println(user)
//
//
//	date, _:= time.Parse("2006/01/02", "2019/12/2") //根据
//	fmt.Println("date", date, date.Unix())
//
//	//
//	//timeNum := getRandTime("2019/12/4")
//	//fmt.Println("timeNum ", timeNum, time.Unix(int64(timeNum),0))
//
//	timeList := getTimeList("2019/12/4", 174)
//	fmt.Println(len(timeList))
//	for i:=0; i<174; i++ {
//		timeNum := timeList[0]
//		timeList = append(timeList[1:])
//		fmt.Println(time.Unix(int64(timeNum),0))
//	}
//	//for _, v := range timeList {
//	//	fmt.Println(time.Unix(int64(v),0))
//	//}
//
//
//	//data := RummyData{
//	//	CreatedAt: time.Now(),
//	//	Uid: 100,
//	//	Region: "india",
//	//	PlayType: 113,
//	//	PlaySubType: 1,
//	//	Level: 0.01,
//	//	PlatformCommission: 1.2,
//	//	RefId: "roomid2222",
//	//
//	//}
//	//writeRummyData(&data)
//}
//


//四舍五入取进度
func GetPrecision(value float32, precision int) float32 {
	if precision <= 0 {
		operValue := float32(int32(value*1+0.5)) / float32(1)
		return operValue
	} else if precision == 1 {
		//取1位小数
		operValue := float32(int32(value*10+0.5)) / float32(10)
		return operValue
	} else if precision == 2 {
		//取2位小数
		operValue := float32(int32(value*100+0.5)) / float32(100)
		return operValue
	} else if precision == 3 {
		//取3位小数
		operValue := float32(int32(value*1000+0.5)) / float32(1000)
		return operValue
	} else {
		//取4位小数
		operValue := float32(int32(value*10000+0.5)) / float32(10000)
		return operValue
	}
}


func CreatePayNum() string {
	h := md5.New()
	_, _ = io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
	cipherStr := h.Sum(nil)
	payNum := hex.EncodeToString(cipherStr)
	fmt.Println("payNum:",payNum)
	return payNum
}
func GetRandStr() string {
	rr := rand.New(rand.NewSource(time.Now().UnixNano() * rand.Int63n(9999)))
	max := 100
	min := 0
	num := rr.Intn(max - min + 1) + min
	payNum := fmt.Sprintf("%02d", num)
	fmt.Println("GetRandStr:",payNum)
	return payNum
}

func main() {

	//initMysql()
	////test()
	//
	////插入数据
	////insertData()
	//
	//if database != nil {
	//	defer database.Close()
	//}


	dateStr := time.Unix(int64(1575389526), 0).Format("2006-01-02 15:04:05")
	fmt.Println(dateStr)

	fmt.Println(GetPrecision(0.125, 2))


	num := float32(0)
	if num == 0 {
		fmt.Println("num ", num)
	}

	str := "MAL_D_1_855752656A6EAA4761507E25B3828912" //MAL_D_1_85575 2656A 6EAA4 76150 7E 25B3828912

	str = CreatePayNum()
	str = str[0:28] + GetRandStr()
	fmt.Println(str)




	str = CreatePayNum()
	str = str[0:28] + GetRandStr()
	fmt.Println(str)


	userId := strconv.Itoa(int(3659118))
	fmt.Println(userId)

	usdtAmount, err := strconv.ParseFloat("1000", 32)
	fmt.Println(usdtAmount, err)

	bestReward := float32(10) * 0.01 * float32(333)  * float32(73)
	bestReward = bestReward * 1.000
	fmt.Println(bestReward)

	timeNum2 := time.Now().Unix()
	lastTime := time.Unix(int64(timeNum2),0)

	fmt.Println(timeNum2, reflect.TypeOf(lastTime), lastTime)

	str = "eee%sww%s"
	rs := strings.Count(str, "%s")
	fmt.Println("rs", rs)

	//test2()
	//test3()
	test4()
}

func test2(){
	type ResData struct {
		Name string `json:"name"`
	}
	type Res struct {
		Status int `json:"status"`
		Transaction_details map[string]ResData `json:transaction_details`
	}
	str := `{
    "status": 1,
    "transaction_details": {
        "MAL_D_14_1E8B817CFA627DA5ED39697AE41DD865": {
            "name": "12524376981"
}}}`

	res := &Res{}
	err := json.Unmarshal([]byte(str), res)
	fmt.Printf("res:%+v, err:%v \n", res, err)

	fmt.Printf("detail:%v \n", res.Transaction_details["test"].Name)
}


type InpayWithdrawRes struct {
	Code    int32                `json:"code"`
	Message string               `json:"message"`
	Data    InpayWithdrawResData `json:"data"`
	Errno   int32                `json:"errno"`
}
type InpayWithdrawResData struct {
	Result string  `json:"result"`
	Order  int32 `json:"order"`
}
func test3() {
	bodyData := `{"code":1,"message":"The system payout channel total_fee range is50-200000 ","data":[],"errno":15}`
	bodyData = strings.Replace(bodyData, ":[]", ":null", 1)
	fmt.Printf("\napiRes:%+v ", bodyData)
	apiRes := &InpayWithdrawRes{}
	err := json.Unmarshal([]byte(bodyData), apiRes)
	fmt.Printf("\napiRes:%+v, err:%v \n", apiRes, err)
}

func test4() {
	var ch chan int
	ch = make(chan int, 1)
	ch2 := make(chan int, 1)
	go func(){
		select {
		case ch <- 10:
			fmt.Println("___1")
		//case <-ch:
		//	fmt.Println("___2")
		//case ch <- 0:
		//	fmt.Println("___3")
		default:
			fmt.Println("__default")

		}
	}()
	time.Sleep(1)
	go func(){
		select {
		case ch222 := <- ch2:
			fmt.Println("_2__1", ch222)
		}

		select {
		case id := <- ch:
			fmt.Println("_2__1 ", id)
		default:
			fmt.Println("_2_default")
		}
	}()


time.Sleep(5)

}